package com.zenithmind.news.controller;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.news.mapper.NewsMapper.NewsStatistics;
import com.zenithmind.news.mapper.NewsMapper.TagStatistics;
import com.zenithmind.news.mapper.NewsMapper.NewsTrend;
import com.zenithmind.news.pojo.dto.NewsCreateDTO;
import com.zenithmind.news.pojo.dto.StatusUpdateRequest;
import com.zenithmind.news.pojo.vo.NewsVO;
import com.zenithmind.news.service.NewsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 新闻控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Tag(name = "新闻管理", description = "新闻相关接口")
@RestController
@RequestMapping("/api/zenithMind/v1/news")
@RequiredArgsConstructor
public class NewsController {

    private final NewsService newsService;

    @Operation(summary = "创建新闻", description = "创建新的新闻文章")
    @PostMapping
    public Result<NewsVO> createNews(@Valid @RequestBody NewsCreateDTO createDTO) {
        NewsVO news = newsService.createNews(createDTO);
        return Result.success(news);
    }

    @Operation(summary = "分页查询新闻列表", description = "分页查询新闻列表")
    @GetMapping
    public Result<PageResult<NewsVO>> getNewsPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryId,
            @Parameter(description = "新闻状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "新闻类型") @RequestParam(required = false) Integer type,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        PageResult<NewsVO> result = newsService.getNewsPage(current, size, categoryId, 
                                                           status, type, keyword, startTime, endTime);
        return Result.success(result);
    }

    @Operation(summary = "查询新闻详情", description = "根据ID查询新闻详情")
    @GetMapping("/{id}")
    public Result<NewsVO> getNewsById(@Parameter(description = "新闻ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        NewsVO news = newsService.getNewsById(id, userId);
        return Result.success(news);
    }

    @Operation(summary = "更新新闻", description = "更新新闻信息")
    @PutMapping("/{id}")
    public Result<Boolean> updateNews(
            @Parameter(description = "新闻ID") @PathVariable String id,
            @Valid @RequestBody NewsCreateDTO updateDTO) {
        Boolean result = newsService.updateNews(id, updateDTO);
        return Result.success(result);
    }

    @Operation(summary = "删除新闻", description = "删除指定新闻")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        Boolean result = newsService.deleteNews(id);
        return Result.success(result);
    }

    @Operation(summary = "发布新闻", description = "发布指定新闻")
    @PostMapping("/{id}/publish")
    public Result<Boolean> publishNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        Boolean result = newsService.publishNews(id);
        return Result.success(result);
    }

    @Operation(summary = "下架新闻", description = "下架指定新闻")
    @PostMapping("/{id}/unpublish")
    public Result<Boolean> unpublishNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        Boolean result = newsService.unpublishNews(id);
        return Result.success(result);
    }

    @Operation(summary = "更新新闻状态", description = "更新指定新闻的状态")
    @PutMapping("/{id}/status")
    public Result<Boolean> updateNewsStatus(
            @Parameter(description = "新闻ID") @PathVariable String id,
            @Parameter(description = "状态") @RequestBody StatusUpdateRequest request) {
        Boolean result = newsService.updateNewsStatus(id, request.getStatus());
        return Result.success(result);
    }

    @Operation(summary = "审核新闻", description = "审核指定新闻")
    @PostMapping("/{id}/review")
    public Result<Boolean> reviewNews(
            @Parameter(description = "新闻ID") @PathVariable String id,
            @Parameter(description = "是否通过") @RequestParam Boolean approved,
            @Parameter(description = "审核意见") @RequestParam(required = false) String comment) {
        Boolean result = newsService.reviewNews(id, approved, comment);
        return Result.success(result);
    }

    @Operation(summary = "查询热门新闻", description = "查询热门新闻列表")
    @GetMapping("/hot")
    public Result<List<NewsVO>> getHotNews(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<NewsVO> news = newsService.getHotNews(limit);
        return Result.success(news);
    }

    @Operation(summary = "查询推荐新闻", description = "查询个性化推荐新闻")
    @GetMapping("/recommend")
    public Result<List<NewsVO>> getRecommendNews(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<NewsVO> news = newsService.getRecommendNews(userId, limit);
        return Result.success(news);
    }

    @Operation(summary = "查询置顶新闻", description = "查询置顶新闻列表")
    @GetMapping("/top")
    public Result<List<NewsVO>> getTopNews(
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "5") Integer limit) {
        List<NewsVO> news = newsService.getTopNews(categoryId, limit);
        return Result.success(news);
    }

    @Operation(summary = "查询相关新闻", description = "查询相关新闻列表")
    @GetMapping("/{id}/related")
    public Result<List<NewsVO>> getRelatedNews(
            @Parameter(description = "新闻ID") @PathVariable String id,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "5") Integer limit) {
        List<NewsVO> news = newsService.getRelatedNews(id, limit);
        return Result.success(news);
    }

    @Operation(summary = "根据标签查询新闻", description = "根据标签查询新闻列表")
    @GetMapping("/tags")
    public Result<List<NewsVO>> getNewsByTags(
            @Parameter(description = "标签列表") @RequestParam List<String> tags,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<NewsVO> news = newsService.getNewsByTags(tags, limit);
        return Result.success(news);
    }

    @Operation(summary = "搜索新闻", description = "根据关键词搜索新闻")
    @GetMapping("/search")
    public Result<List<NewsVO>> searchNews(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<NewsVO> news = newsService.searchNews(keyword, limit);
        return Result.success(news);
    }

    @Operation(summary = "点赞新闻", description = "点赞指定新闻")
    @PostMapping("/{id}/like")
    public Result<Boolean> likeNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = newsService.likeNews(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "取消点赞新闻", description = "取消点赞指定新闻")
    @DeleteMapping("/{id}/like")
    public Result<Boolean> unlikeNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = newsService.unlikeNews(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "收藏新闻", description = "收藏指定新闻")
    @PostMapping("/{id}/favorite")
    public Result<Boolean> favoriteNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = newsService.favoriteNews(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "取消收藏新闻", description = "取消收藏指定新闻")
    @DeleteMapping("/{id}/favorite")
    public Result<Boolean> unfavoriteNews(@Parameter(description = "新闻ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = newsService.unfavoriteNews(id, userId);
        return Result.success(result);
    }

    @Operation(summary = "分享新闻", description = "分享指定新闻")
    @PostMapping("/{id}/share")
    public Result<Boolean> shareNews(
            @Parameter(description = "新闻ID") @PathVariable String id,
            @Parameter(description = "分享平台") @RequestParam String platform) {
        String userId = UserContext.getUserId();
        Boolean result = newsService.shareNews(id, userId, platform);
        return Result.success(result);
    }

    @Operation(summary = "批量更新新闻状态", description = "批量更新新闻状态")
    @PostMapping("/batch/status")
    public Result<Boolean> batchUpdateStatus(
            @Parameter(description = "新闻ID列表") @RequestParam List<String> newsIds,
            @Parameter(description = "新闻状态") @RequestParam Integer status) {
        Boolean result = newsService.batchUpdateStatus(newsIds, status);
        return Result.success(result);
    }

    @Operation(summary = "获取新闻统计信息", description = "获取新闻统计信息")
    @GetMapping("/statistics")
    public Result<NewsStatistics> getNewsStatistics(
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        NewsStatistics statistics = newsService.getNewsStatistics(categoryId, startTime, endTime);
        return Result.success(statistics);
    }

    @Operation(summary = "获取热门标签", description = "获取热门标签列表")
    @GetMapping("/tags/hot")
    public Result<List<TagStatistics>> getHotTags(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<TagStatistics> tags = newsService.getHotTags(limit);
        return Result.success(tags);
    }

    @Operation(summary = "获取新闻趋势", description = "获取新闻趋势数据")
    @GetMapping("/trend")
    public Result<List<NewsTrend>> getNewsTrend(
            @Parameter(description = "天数") @RequestParam(defaultValue = "7") Integer days) {
        List<NewsTrend> trend = newsService.getNewsTrend(days);
        return Result.success(trend);
    }

    @Operation(summary = "计算新闻热度", description = "计算指定新闻的热度评分")
    @PostMapping("/{id}/hot-score")
    public Result<Double> calculateHotScore(@Parameter(description = "新闻ID") @PathVariable String id) {
        Double hotScore = newsService.calculateHotScore(id);
        return Result.success(hotScore);
    }
}
